package com.boss.salary.service.impl;

import com.boss.common.util.DateUtils;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.dao.*;
import com.boss.salary.entity.SalaryBasedata;
import com.boss.salary.entity.SalaryMonthEnd;
import com.boss.salary.service.ISalaryMonthEndService;
import com.boss.salary.vo.AgencySalaryVO;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SalaryMonthEndServiceImpl implements ISalaryMonthEndService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(SalaryMonthEndServiceImpl.class);

    @Autowired
    private ISalaryMonthEndDao salaryMonthEndDao;
    @Autowired
    private IAgencyVerifyDao agencyVerifyDao;
    @Autowired
    private IAgencySalaryDao agencySalaryDao;
    @Autowired
    private IPersonOperateDao personOperateDao;
    @Autowired
    private ISalaryBasedataDao salaryBasedataDao;

    @Override
    public List<Map<String, Object>> getThirteenSalaryPage(UserDTO userDTO,String agencyId) {
        Map<String, Object> map = agencyVerifyDao.selectStateByAgencyId(agencyId, "salary_month");
        if (CollectionUtils.isEmpty(map) || StringUtils.isEmpty(map.get("salary_month"))) {
            return Collections.emptyList();
        }
        String salaryMonth = String.valueOf(map.get("salary_month"));
//        获取当月工资字段名
        List<AgencySalaryVO> currentcolumnList = agencySalaryDao.selectColumnName(userDTO);
        if (CollectionUtils.isEmpty(currentcolumnList)) {
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
//        获取工资字段名
        List<String> salaryColumns = currentcolumnList.stream().map(AgencySalaryVO::getColumnName).collect(Collectors.toList());
//查询第十三月工资
        List<Map<String, Object>> list = salaryMonthEndDao.selectThirteenSalaryPage(agencyId, salaryMonth, salaryColumns);
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, Object> sum = salaryMonthEndDao.selectThirteenSalarySum(agencyId, salaryColumns);
            sum.put("index", "合计");
            list.add(0, sum);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void physicalDeleteThirteenMonthSalary(String agencyId) {
        salaryMonthEndDao.physicalDeleteThirteenMonthSalary(agencyId);
        salaryMonthEndDao.clearThirteenSalaryByAgencyId(agencyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitThirteenthMonthSalary(List<SalaryMonthEnd> list) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (!CollectionUtils.isEmpty(list)) {
            List<Object[]> objectList = new ArrayList<>();
            String[] columns = list.get(0).getColumnNames().split(",");
            Class<?> clazz = SalaryMonthEnd.class;
            for (SalaryMonthEnd salaryMonthEnd : list) {
                if (list.indexOf(salaryMonthEnd) == 0) {
                    continue;
                }
                List<Object> params = new ArrayList<>();
                params.add(String.valueOf(DateUtils.getCurrentTimeStamp()));//修改时间
                for (String column : columns) {
                    Method getMethod = clazz.getDeclaredMethod("get" + column.substring(0, 1).toUpperCase() + column.substring(1));
                    params.add(getMethod.invoke(salaryMonthEnd));
                }
                params.add(salaryMonthEnd.getId());
                objectList.add(params.toArray());
            }
            salaryMonthEndDao.batchUpdateThirteenMonthSalary(columns, objectList);
            for(SalaryMonthEnd salaryMonthEnd : list){
                if (list.indexOf(salaryMonthEnd) == 0) {
                    continue;
                }
                String personId = salaryMonthEnd.getPersonId();
                String agencyId = salaryMonthEnd.getAgencyId();
                salaryMonthEndDao.clearThirteenSalaryByPersonAndAgencyId(personId, agencyId);
                salaryMonthEndDao.updateThirteenSalaryByPersonAndAgencyId(personId, agencyId, salaryMonthEnd.getS1());
            }
        }
    }

    @Override
    public Integer getPaidWagesCount(String agencyId,UserDTO userDTO) {
        //查询控制 是否允许为0上报工资
        String zeroAble= salaryMonthEndDao.getZeroAble(userDTO.getProvince());
        if("null".equals(zeroAble)||null==zeroAble){
            zeroAble="1";
        }
        List<String> computeColumns=new ArrayList<>();
        List<SalaryBasedata> salaryBasedatas=salaryBasedataDao.selectComputeColumn(userDTO.getProvince());
        for(SalaryBasedata sb:salaryBasedatas){
            computeColumns.add(sb.getSalaryCode());
        }
        return salaryMonthEndDao.getPaidWagesCount(agencyId,zeroAble, computeColumns);
    }

    @Override
    public Integer getUnreviewedPersonCount(String agencyId) {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("agencyId",agencyId);
        queryParam.put("flag","1");
        return personOperateDao.getPersonInfoChangeOperateTotal(queryParam);
    }
}
